<template>
  <div class="body-container layout-padding">
    <el-form label-width="80px" style="margin-bottom: 10px">
      <el-row :gutter="10">
        <el-col :span="4">
          <el-form-item label="仓库名称">
            <el-select filterable clearable v-model="state.sd.cwhname" placeholder="仓库名称">
              <el-option  v-for="item in state.whList" :key="item.cwhcode" :label="item.cwhname" :value="item.cwhname" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="存货名称">
            <el-input v-model="state.sd.cinvname" placeholder="存货名称"/>
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-form-item label="规格型号">
            <el-input v-model="state.sd.cinvstd" placeholder="规格型号"/>
          </el-form-item>
        </el-col>
        <el-col :span="1">
          <el-form-item label="现存量>0">
            <el-checkbox v-model="state.sd.iquantityflag" />
          </el-form-item>
        </el-col>
        <el-col :span="1">
          <el-form-item label="未盘点">
            <el-checkbox v-model="state.sd.npdflag" />
          </el-form-item>
        </el-col>
        <el-col :span="1">
          <el-form-item label="已盘点">
            <el-checkbox v-model="state.sd.pdflag" />
          </el-form-item>
        </el-col>
        <el-col :span="2">
          <el-form-item label="差异">
            <el-checkbox v-model="state.sd.czquantityflag" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-button size="default" type="primary" class="ml5" @click="searchCurrentStore">
            <el-icon><ele-Search /></el-icon>查询
          </el-button>
          <el-button size="default" type="primary" class="ml5" @click="exportCurrentStore" :loading="state.exportBtnLoading">
            <el-icon><ele-Download /></el-icon>导出
          </el-button>
          <el-button size="default" type="warning" class="ml5" @click="createCsSnapshotPopup"  v-auths="[state.permissionType.sysAdmin, state.permissionType.pddata_pdrecordsnapshot]"  >
            <el-icon><ele-Plus /></el-icon>盘点记录
          </el-button>
          <el-popconfirm title="确定要清空盘点数据吗?" @confirm="clearKc"  >
            <template #reference>
              <el-button size="default" type="danger" class="ml5" v-auths="[state.permissionType.sysAdmin, state.permissionType.pddata_clearpd]">
                <el-icon><ele-Delete /></el-icon>清空盘点
              </el-button>
            </template>
          </el-popconfirm>
          <el-popconfirm title="确定要清空所选的盘点数据吗?" @confirm="clearKcSelect"  >
            <template #reference>
              <el-button size="default" type="danger" class="ml5" v-auths="[state.permissionType.sysAdmin, state.permissionType.pddata_clearpd]">
                <el-icon><ele-Delete /></el-icon>清空所选
              </el-button>
            </template>
          </el-popconfirm>
        </el-col>
      </el-row>
    </el-form>
    <el-table :data="state.csObj.list" border style="width: 100%" @selection-change="handleSelectionChange" :row-class-name="settableclass">
      <el-table-column type="selection" width="55" />
      <el-table-column label="仓库名称" prop="cwhname"></el-table-column>
      <el-table-column label="存货编码" prop="cinvcode"></el-table-column>
      <el-table-column label="存货名称" prop="cinvname"></el-table-column>
      <el-table-column label="规格型号" prop="cinvstd"></el-table-column>
<!--      <el-table-column label="批号" prop="cbatch"></el-table-column>-->
      <el-table-column label="单位名称" prop="ccomunitname"></el-table-column>
      <el-table-column label="现存数量" prop="iquantity"></el-table-column>
      <el-table-column label="盘点数量" prop="pdquantity"></el-table-column>
      <el-table-column label="盘亏盘盈" prop="czquantity"></el-table-column>
      <el-table-column label="盘点人员" prop="pduser"></el-table-column>
      <el-table-column label="盘点时间">
        <template v-slot="scope">
          <DateFormat :value="scope.row.lasttbdate" :format="'YYYY-MM-DD HH:mm'" v-if="scope.row.lasttbdate"></DateFormat>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination class="mt15" background layout="total,sizes, prev, pager, next"
                   @current-change="loadPdNow" @size-change="loadPdNow" :total="state.csObj.total"
                   v-model:current-page="state.sd.pageNum" v-model:page-size="state.sd.pageSize" :page-sizes="state.sd.pageSizes">
    </el-pagination>
    <el-dialog title="盘点记录" v-model="state.ssForm.snapshotTitleVisible" :close-on-click-modal="false" width="888px">
      <el-form ref="ssForm" label-width="120px">
        <el-form-item label="记录标题" prop="title">
          <el-input v-model="state.ssForm.title" placeholder="记录标题" />
        </el-form-item>
        <el-form-item label="盘点计划" prop="planId">
          <el-select v-model="state.ssForm.planId" placeholder="盘点计划" @change="planChange" clearable>
            <el-option v-for="item in state.planList" :key="item.id" :label="item.title" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="仓库选择" prop="selectedCangKuList">
          <el-checkbox-group v-model="state.ssForm.selectedCangKuList">
            <el-checkbox :label="item.cwhname" v-for="(item,index) in state.whList"  :key="item.id" />
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="数据范围" prop="nowMonth">
          <el-checkbox v-model="state.ssForm.nowMonth" label="是否只有本月盘点数据生成盘点记录" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="createCsSnapshot" size="default" :loading="state.createCsSnapshotLoading">保存记录</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup name="currentStoreIndex">
import request from '/@/utils/request';
import { ElMessage } from 'element-plus';
import mittBus from '/@/utils/mitt';
import PermissionType from "/@/utils/PermissionType";
import {reactive, ref, onMounted, onUnmounted, defineAsyncComponent} from "vue";
import { useRouter } from "vue-router";
const router = useRouter();

const baseURL= import.meta.env.VITE_API_URL;

const state = reactive({
  permissionType:PermissionType,
  sd: {
    pageNum: 1,
    pageSize: 100,
    pageSizes: [50, 100, 150, 200],
    cwhname:'',
    cinvcode:'',
    cinvname:'',
    cinvstd:'',
    iquantityflag:true,
    pdflag:false,
    czquantityflag:false,
    npdflag:false,
  },
  ssForm:{
    snapshotTitleVisible : false,
    selectedCangKuList:[],
    nowMonth:false,
    title:'',
    planId:undefined
  },
  csObj: {},
  planList : [],
  whList : [],
  exportBtnLoading : false,
  createCsSnapshotLoading : false,
  selectedAutoIdArray:[],
})
const searchCurrentStore = ()=>{
  state.sd.pageNum = 1;
  loadPdNow();
}
const loadPdNow = ()=>{
  request({
    url: '/currentstore/pagepdnow',
    data: state.sd
  }).then(res => {
    const { data } = res
    state.csObj = data
  })
}
const loadPlan = ()=>{
  request({
    url: '/plan/listfabuplan',
    data: {}
  }).then(res => {
    const { data } = res
    state.planList = data
  })
}
const loadWhList = ()=>{
  request({
    url: '/cangku/listuserwh',
    data: {}
  }).then(res => {
    const { data } = res
    state.whList = data
  })
}
/*plan变更需要重新加载仓库数据*/
const loadUserAndPlanWhList = (planId)=>{
  request({
    url: '/cangku/listuserandplanwh',
    data: {planId : planId}
  }).then(res => {
    const { data } = res
    state.whList = data
  })
}
const exportCurrentStore = ()=>{
  state.exportBtnLoading = true;
  request({
    url: '/currentstore/exportpdnow',
    data: state.sd
  }).then(res => {
    state.exportBtnLoading = false;
    const { data } = res
    const url = baseURL + "/profile/temp/" + data
    let a = document.createElement('a')
    a.href = url;
    a.click();
  })
}
const createCsSnapshotPopup = ()=>{
  state.ssForm.snapshotTitleVisible = true
}
const planChange = (value)=>{
  state.ssForm.selectedCangKuList = [];
  if(value) {
    loadUserAndPlanWhList(value)
  }else {
    loadWhList();
  }
}
const createCsSnapshot = ()=>{
  let selectedWhcodes = []
  state.ssForm.selectedCangKuList.forEach(cwhname => {
    let fArray = state.whList.filter(ck => ck.cwhname === cwhname)
    fArray.forEach(fry =>{
      selectedWhcodes.push(fry.cwhcode)
    })
  })
  if(selectedWhcodes.length <= 0){
    ElMessage.error("请选择仓库")
    return
  }
  if(!state.ssForm.title){
    ElMessage.error("请输入库存记录标题")
    return
  }
  state.createCsSnapshotLoading = true;
  request({
    url: '/cssnapshot/createcssnapshot',
    data: {title : state.ssForm.title, planId:state.ssForm.planId, selectedWhcodes : selectedWhcodes, nowMonth: state.ssForm.nowMonth ? 1 : 0}
  }).then(res => {
    if(res.code === '200'){
      ElMessage.success("盘点记录生成成功")
      state.createCsSnapshotLoading = false;
      state.ssForm.snapshotTitleVisible = false;
      state.ssForm.selectedCangKuList = [];
      state.ssForm.title = '';
      state.ssForm.planId = undefined;
      loadWhList();
    }
  }).catch(e =>{
    state.createCsSnapshotLoading = false;
  })
}

const handleSelectionChange = (selectedRow)=>{
  state.selectedAutoIdArray = [];
  if(Array.isArray(selectedRow)){
    selectedRow.forEach((row)=>{
      state.selectedAutoIdArray.push(row.autoid)
    })
  }
}
const clearKc = ()=>{
  if(!state.sd.cwhname){
    ElMessage.error("请选择仓库")
    return
  }
  request({
    url: '/currentstore/clearkc',
    data: {cwhname : state.sd.cwhname}
  }).then(res => {
    if(res.code === '200'){
      ElMessage.success("操作成功")
      loadPdNow();
    }
  })
}
const clearKcSelect = ()=>{
  if(state.selectedAutoIdArray.length <= 0){
    ElMessage.error("请选择清空数据")
    return
  }
  request({
    url: '/currentstore/clearselectkc',
    data: {selectedAutoIdArray : state.selectedAutoIdArray}
  }).then(res => {
    if(res.code === '200'){
      ElMessage.success("操作成功")
      state.selectedAutoIdArray = []
      loadPdNow();
    }
  })
}
const settableclass = ( {row, rowIndex})=>{
  if(row.czquantity) {
    if(row.pdquantity-row.czquantity !== row.iquantity){
      //return "warning-row"
      return ""
    }
  }
  return "";
}
onMounted(()=>{
  loadPlan();
  loadWhList();
  loadPdNow();
})
onUnmounted(()=>{

})
</script>
<style scoped lang="scss">
</style>
